import React, { useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import { AiEditor } from "aieditor";
import "aieditor/dist/style.css";

const AiEditorComponent = forwardRef(({ 
  value = '', 
  onChange, 
  placeholder = "点击输入内容...",
  height = "600px",
  ...props 
}, ref) => {
  const divRef = useRef(null);
  const editorRef = useRef(null);

  // 暴露编辑器实例给父组件
  useImperativeHandle(ref, () => ({
    getEditor: () => editorRef.current,
    getContent: () => editorRef.current?.getHtml() || '',
    setContent: (content) => editorRef.current?.setContent(content),
    focus: () => editorRef.current?.focus(),
    blur: () => editorRef.current?.blur()
  }));

  useEffect(() => {
    if (divRef.current && !editorRef.current) {
      const aiEditor = new AiEditor({
        element: divRef.current,
        placeholder,
        content: value,
        onChange: (editor) => {
          const content = editor.getHtml();
          onChange && onChange(content);
        },
        // 工具栏配置
        toolbarKeys: [
          "undo", "redo", "brush", "eraser",
          "|", "heading", "font-family", "font-size",
          "|", "bold", "italic", "underline", "strike", "link", "code", "subscript", "superscript",
          "|", "highlight", "font-color",
          "|", "align", "line-height",
          "|", "bullet-list", "ordered-list", "indent-decrease", "indent-increase", "break",
          "|", "image", "video", "table", "hr", "code-block", "quote",
          "|", "printer", "fullscreen", "ai"
        ],
        // AI 配置
        ai: {
          models: {
            openai: {
              apiKey: process.env.REACT_APP_OPENAI_API_KEY || "",
              endpoint: process.env.REACT_APP_OPENAI_ENDPOINT || "https://api.openai.com",
            }
          }
        },
        // 图片上传配置
        image: {
          uploadUrl: "http://211.86.197.10:9091/api/upload/image",
          uploadHeaders: () => ({
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          })
        },
        // 视频上传配置
        video: {
          uploadUrl: "http://211.86.197.10:9091/api/upload/video",
          uploadHeaders: () => ({
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          })
        }
      });

      editorRef.current = aiEditor;
    }

    return () => {
      if (editorRef.current) {
        editorRef.current.destroy();
        editorRef.current = null;
      }
    };
  }, []);

  // 当 value 从外部改变时更新编辑器内容
  useEffect(() => {
    if (editorRef.current && value !== editorRef.current.getHtml()) {
      editorRef.current.setContent(value);
    }
  }, [value]);

  return (
    <div 
      ref={divRef} 
      style={{ height, border: '1px solid #d9d9d9', borderRadius: '6px' }}
      {...props}
    />
  );
});

AiEditorComponent.displayName = 'AiEditorComponent';

export default AiEditorComponent;